// env-template.js - Environment template generator
import { printSuccess, printError, printWarning } from '../utils.js';
import { existsSync } from 'fs';
import { promises as fs } from 'fs';
import path from 'path';

/**
 * Generate .env template with configuration instructions
 */
export async function generateEnvTemplate(workingDir = process.cwd(), force = false) {
  const envPath = path.join(workingDir, '.env');

  // Check if .env already exists
  if (existsSync(envPath) && !force) {
    printWarning('⚠️  .env file already exists');
    console.log('Use --force to overwrite existing .env file');
    return { exists: true, created: false };
  }

  const template = `# Agentic Flow Configuration
# Generated by claude-flow init --env
# Created: ${new Date().toISOString()}

# ============================================
# REQUIRED FOR REASONINGBANK MEMORY
# ============================================
# Without these, ReasoningBank will fall back to heuristic mode (regex matching)
# For actual learning and memory consolidation, you MUST provide API keys

# Anthropic API key for Claude models (sk-ant-...)
# Get your key: https://console.anthropic.com/settings/keys
ANTHROPIC_API_KEY=

# OpenRouter API key for alternative models (sk-or-v1-...)
# Get your key: https://openrouter.ai/keys
# Enables 99% cost savings with DeepSeek R1 for judge/distill
OPENROUTER_API_KEY=

# Google Gemini API key (optional, for free tier)
# Get your key: https://aistudio.google.com/app/apikey
GOOGLE_GEMINI_API_KEY=

# ============================================
# MODEL CONFIGURATION
# ============================================
# Default model for completions (Claude 3.5 Sonnet v2 - latest)
COMPLETION_MODEL=claude-3-5-sonnet-20241022

# Default provider (anthropic, openrouter, onnx, gemini)
PROVIDER=anthropic

# ============================================
# ADVANCED: REASONINGBANK COST OPTIMIZATION
# ============================================
# To use cheap models for memory operations (46% savings):
# 1. Set OPENROUTER_API_KEY above
# 2. Create .swarm/reasoningbank.yaml with:
#
# reasoningbank:
#   judge:
#     model: "deepseek/deepseek-r1"
#     max_tokens: 512
#     temperature: 0
#   distill:
#     model: "deepseek/deepseek-r1"
#     max_tokens: 2048
#     temperature: 0.3
#   embeddings:
#     provider: "openrouter"
#     model: "deepseek/deepseek-r1"
#     dimensions: 1024
#
# This keeps Claude for main work but uses DeepSeek for memory (99% cheaper)
# Result: $0.37 → $0.20 per task with memory (46% savings!)

# ============================================
# OPTIONAL API KEYS
# ============================================
# Perplexity API key (for GOAP search integration)
PERPLEXITY_API_KEY=

# Hugging Face API key (for ONNX models)
HUGGINGFACE_API_KEY=

# E2B API keys (for Flow Nexus sandbox deployment)
E2B_API_KEY=
E2B_ACCESS_TOKEN=

# Supabase configuration (for Flow Nexus cloud features)
SUPABASE_URL=
SUPABASE_ANON_KEY=
SUPABASE_ACCESS_TOKEN=
SUPABASE_PROJECT_ID=

# ============================================
# WHAT HAPPENS WITHOUT .env?
# ============================================
# Without this file:
# 1. No automatic environment variable loading
# 2. ReasoningBank falls back to heuristic judgment (regex-based)
# 3. No actual learning or memory consolidation
# 4. Demo will appear to work but uses pattern matching only
#
# You can still work without .env by:
# - Manually exporting environment variables
# - Or passing inline with commands
#
# But using .env is recommended for convenience and security.

# ============================================
# SECURITY NOTES
# ============================================
# 1. NEVER commit this file to git (it's in .gitignore)
# 2. Use different keys for dev/staging/production
# 3. Rotate keys regularly
# 4. Use key-specific permissions when possible
`;

  // Write template
  try {
    await fs.writeFile(envPath, template, 'utf8');
    printSuccess('✅ Created .env template file');
    return { exists: false, created: true, path: envPath };
  } catch (error) {
    printError(`❌ Failed to create .env template: ${error.message}`);
    return { exists: false, created: false, error: error.message };
  }
}

/**
 * Check if .env exists and has required keys
 */
export async function checkEnvConfig(workingDir = process.cwd()) {
  const envPath = path.join(workingDir, '.env');

  if (!existsSync(envPath)) {
    return {
      exists: false,
      hasApiKeys: false,
      message: '.env file not found'
    };
  }

  try {
    const envContent = await fs.readFile(envPath, 'utf8');

    // Check for API keys (not commented out and not empty)
    const hasAnthropicKey = /^ANTHROPIC_API_KEY=[^\s]+$/m.test(envContent);
    const hasOpenRouterKey = /^OPENROUTER_API_KEY=[^\s]+$/m.test(envContent);
    const hasGeminiKey = /^GOOGLE_GEMINI_API_KEY=[^\s]+$/m.test(envContent);

    return {
      exists: true,
      hasApiKeys: hasAnthropicKey || hasOpenRouterKey || hasGeminiKey,
      keys: {
        anthropic: hasAnthropicKey,
        openrouter: hasOpenRouterKey,
        gemini: hasGeminiKey
      },
      message: 'Configuration found'
    };
  } catch (error) {
    return {
      exists: true,
      hasApiKeys: false,
      message: `Error reading .env: ${error.message}`
    };
  }
}

/**
 * Show .env setup instructions
 */
export function showEnvSetupInstructions() {
  console.log('\n📋 Setting up .env for ReasoningBank capabilities:\n');
  console.log('1. Create .env file:');
  console.log('   claude-flow init --env\n');
  console.log('2. Add your API keys to .env:');
  console.log('   ANTHROPIC_API_KEY=sk-ant-...');
  console.log('   OPENROUTER_API_KEY=sk-or-v1-...  # Optional: 99% cost savings\n');
  console.log('3. Get API keys:');
  console.log('   • Anthropic: https://console.anthropic.com/settings/keys');
  console.log('   • OpenRouter: https://openrouter.ai/keys (for cost optimization)\n');
  console.log('💡 Without API keys:');
  console.log('   • ReasoningBank falls back to regex pattern matching (no learning)');
  console.log('   • Memory operations will appear to work but won\'t actually learn\n');
  console.log('💰 Cost optimization:');
  console.log('   • Use OpenRouter + DeepSeek R1 for judge/distill (99% cheaper)');
  console.log('   • See: docs/REASONINGBANK-COST-OPTIMIZATION.md\n');
}
